package com.example.captchademo.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captchademo.Controller.Model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private final static long delay = 60_000L;
    //
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //设置返回类型
        response.setContentType("image/jpeg");
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        try {
            lineCaptcha.write(response.getOutputStream());
            //保存code
            session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
            //保存当前时间
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(lineCaptcha.getCode());
    }
    //
    @RequestMapping("/check")
    public Boolean checkCaptcha(String input,HttpSession session) {
        if (!StringUtils.hasLength(input)) {
            return false;
        }
        //获取session中的时间
        long savedDate = (long)session.getAttribute(captchaProperties.getSession().getDate());
        long curDate = System.currentTimeMillis();
        if (curDate - savedDate > delay) {
            return false;
        }
        //获取session中的code
        String savedCode = (String)session.getAttribute(captchaProperties.getSession().getKey());
        return input.equalsIgnoreCase(savedCode);
    }
}
